package com.tevintao.marketingsystem.tool;

import com.tevintao.marketingsystem.log.LogManager;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;


public class UploadFileTool {


    /* 上传文件至Server的方法 */
    public static String uploadFile(String urlPath, String filePath) {

        File uploadFile = new File(filePath);
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
//        URL url = new URL("http://192.168.1.100:8000/chat/updateFile?pm1=1&pm2=2");
        URL url;
        try {
            url = new URL(urlPath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }

        HttpURLConnection con;
        try {
            con = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        if (null == con) {
            LogManager.getInstance().logError("打开url失败");
            return null;
        }
            /* 允许Input、Output，不使用Cache */
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);

        // 设置http连接属性
        try {
            con.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);

        DataOutputStream ds;
        try {
            ds = new DataOutputStream(con.getOutputStream());

            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "
                    + "name=\"myfile\";filename=\"" + uploadFile.getName() + "\"" + end);
            ds.writeBytes(end);

            // 取得文件的FileInputStream
            FileInputStream fStream = new FileInputStream(uploadFile);
            /* 设置每次写入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length;
            /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1) {
                /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

            fStream.close();
            ds.flush();
            /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuilder b = new StringBuilder();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            /* 将Response显示于Dialog */
            LogManager.getInstance().logError("上传件成功" + b.toString().trim());
            /* 关闭DataOutputStream */
            ds.close();
            return b.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /* 上传文件至Server的方法 */
    public static String uploadFile(String urlPath, String filePath, String fileName) {

        File uploadFile = new File(filePath);
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
//        URL url = new URL("http://192.168.1.100:8000/chat/updateFile?pm1=1&pm2=2");
        URL url;
        try {
            url = new URL(urlPath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }

        HttpURLConnection con;
        try {
            con = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        if (null == con) {
            LogManager.getInstance().logError("打开url失败");
            return null;
        }
            /* 允许Input、Output，不使用Cache */
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);

        // 设置http连接属性
        try {
            con.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);

        DataOutputStream ds;
        try {
            ds = new DataOutputStream(con.getOutputStream());

            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; "
                    + "name=\"myfile\";filename=\"" + fileName + "\"" + end);
            ds.writeBytes(end);

            // 取得文件的FileInputStream
            FileInputStream fStream = new FileInputStream(uploadFile);
            /* 设置每次写入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length;
            /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1) {
                /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

            fStream.close();
            ds.flush();
            /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuilder b = new StringBuilder();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            /* 将Response显示于Dialog */
            LogManager.getInstance().logError("上传温条件成功" + b.toString().trim());
            /* 关闭DataOutputStream */
            ds.close();
            return b.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
